<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">



  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=5.1.4">






  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="#定义参数，判断查询参数q是否是isbn号1234567891011121314151617@app.route(&amp;quot;/search/&amp;lt;q&amp;gt;/&amp;lt;page&amp;gt;&amp;quot;)def search(q,page):    &amp;quot;&amp;quot;&amp;quot;    搜索书籍路由    :param q: 关键字 OR isbn    :param page: 页码    &amp;">
<meta property="og:type" content="article">
<meta property="og:title" content="初识鱼书项目">
<meta property="og:url" content="http://imwl.ml/flask框架学习/初识鱼书项目/index.html">
<meta property="og:site_name" content="Get busy living">
<meta property="og:description" content="#定义参数，判断查询参数q是否是isbn号1234567891011121314151617@app.route(&amp;quot;/search/&amp;lt;q&amp;gt;/&amp;lt;page&amp;gt;&amp;quot;)def search(q,page):    &amp;quot;&amp;quot;&amp;quot;    搜索书籍路由    :param q: 关键字 OR isbn    :param page: 页码    &amp;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-14T14:46:34.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="初识鱼书项目">
<meta name="twitter:description" content="#定义参数，判断查询参数q是否是isbn号1234567891011121314151617@app.route(&amp;quot;/search/&amp;lt;q&amp;gt;/&amp;lt;page&amp;gt;&amp;quot;)def search(q,page):    &amp;quot;&amp;quot;&amp;quot;    搜索书籍路由    :param q: 关键字 OR isbn    :param page: 页码    &amp;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://imwl.ml/flask框架学习/初识鱼书项目/">





  <title>初识鱼书项目 | Get busy living</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>
	

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Get busy living</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry,Stay Foolish</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-gitbook">
          <a href="/book/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br>
            
            gitbook
          </a>
        </li>
      
        
        <li class="menu-item menu-item-resume">
          <a href="/resume/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-address-card"></i> <br>
            
            个人简历
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://imwl.ml/flask框架学习/初识鱼书项目/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="WeiLai">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Get busy living">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">初识鱼书项目</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-14T23:07:07+08:00">
                2018-11-14
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/flask/" itemprop="url" rel="index">
                    <span itemprop="name">flask</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>#定义参数，判断查询参数q是否是isbn号<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">@app.route(&quot;/search/&lt;q&gt;/&lt;page&gt;&quot;)</span><br><span class="line">def search(q,page):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    搜索书籍路由</span><br><span class="line">    :param q: 关键字 OR isbn</span><br><span class="line">    :param page: 页码</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    # isbn isbn13 由13个0-9在数字组成</span><br><span class="line">    # isbn10 由10表0-9表数字组组成，中间可能包含&apos; - &apos;</span><br><span class="line"></span><br><span class="line">    isbn_or_key = &apos;key&apos;</span><br><span class="line">    if len(q) == 13 and q.isdigit():</span><br><span class="line">        isbn_or_key = &apos;isbn&apos;</span><br><span class="line">    short_q = q.replace(&apos;-&apos;, &apos;&apos;)</span><br><span class="line">    if &apos;-&apos; in q and len(short_q) == 10 and short_q.isdigit():</span><br><span class="line">        isbn_or_key = &apos;isbn&apos;</span><br><span class="line">    pass</span><br></pre></td></tr></table></figure></p>
<p><strong>知识点：</strong></p>
<ul>
<li>字符串有一个函数isdigit()可以判断是否为数字</li>
<li>in 关键字可以判断一个字符串是否在另一个字符串内</li>
<li>多个逻辑判断排列原则：1.大部分判断结果为假的条件应该放在前面；2.需要查询数据库的操作由于会消耗资源，应该尽量靠后</li>
</ul>
<p>#简单的重构<br>将上一小节的判断语句全都写到search函数中的几个缺点：</p>
<ol>
<li>使得代码非常的臃肿，现在只有两个判断就占用了6行，如果有多个判断，search方法就要爆炸了</li>
<li>如果有其他地方的代码也要进行这个判断，那么就需要再重新写一遍，同样的代码重现在了两个地方</li>
<li>代码可读性查，作为一个路由函数，代码阅读者很难一眼看出路由函数的主要功能。</li>
</ol>
<p>重构后的代码<br><strong>fisher.py</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@app.route(&quot;/search/&lt;q&gt;/&lt;page&gt;&quot;)</span><br><span class="line">def search(q, page):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    搜索书籍路由</span><br><span class="line">    :param q: 关键字 OR isbn</span><br><span class="line">    :param page: 页码</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    isbn_or_key = is_isbn_or_key(q)</span><br></pre></td></tr></table></figure></p>
<p><strong>helper.py</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">def is_isbn_or_key(word):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">        判断word是isbn号还是查询关键字key</span><br><span class="line">        isbn isbn13 由13个0-9在数字组成</span><br><span class="line">        isbn10 由10表0-9表数字组组成，中间可能包含&apos; - &apos;</span><br><span class="line">    :param word:</span><br><span class="line">    :return: key or isbn</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    isbn_or_key = &apos;key&apos;</span><br><span class="line">    if len(word) == 13 and word.isdigit():</span><br><span class="line">        isbn_or_key = &apos;isbn&apos;</span><br><span class="line">    short_word = word.replace(&apos;-&apos;, &apos;&apos;)</span><br><span class="line">    if &apos;-&apos; in word and len(short_word) == 10 and short_word.isdigit():</span><br><span class="line">        isbn_or_key = &apos;isbn&apos;</span><br><span class="line">    return isbn_or_key</span><br></pre></td></tr></table></figure></p>
<p><strong>知识点：</strong></p>
<ul>
<li>其他地方的代码多一点还可以接受，视图函数中不可以，因为视图函数是一个web项目的入口。所有人阅读都是从这里入手，应该把细节屏蔽掉，给阅读者一个选择。</li>
<li>看源码的技巧：先通读整体，了解整体过程，再回过头来了解细节，不要从一开始就深究每一个细节</li>
<li>过多的注释会让代码变的臃肿，尽量使用易懂的函数名来代替注释，保持代码的简洁性<br><strong>使用三元表达式优化</strong><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">import requests</span><br><span class="line">class HTTP:  #class HTTP(object):有无都无所谓</span><br><span class="line"></span><br><span class="line">    @staticmethod</span><br><span class="line">    def get(url,return_json=True):</span><br><span class="line">    </span><br><span class="line">        r = requests.get(url)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        if r.status_code == 200:</span><br><span class="line">            if return_json():</span><br><span class="line">                return r.json()</span><br><span class="line">            else:</span><br><span class="line">                return r.text</span><br><span class="line">        else:</span><br><span class="line">            if return_json:</span><br><span class="line">                return &#123;&#125;</span><br><span class="line">            else:</span><br><span class="line">                return &apos;&apos;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><strong>优化后</strong><br> <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">import requests</span><br><span class="line">class HTTP:  #class HTTP(object):有无都无所谓</span><br><span class="line"></span><br><span class="line">    @staticmethod</span><br><span class="line">    def get(url,return_json=True):</span><br><span class="line">    </span><br><span class="line">        r = requests.get(url)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        if r.status_code != 200:</span><br><span class="line">            return &#123;&#125; if return_json else &apos;&apos;      #特例情况</span><br><span class="line">        return r.json() if return_json else r.text   #正常返回</span><br></pre></td></tr></table></figure></p>
<p><strong>知识点：</strong></p>
<ul>
<li>简化if-else语句的几种方式 1.使用三元表达式 ；2.if+return；3.将if-else里的代码提取成函数</li>
<li>if+return的理解：把最后一句return前的if+return 全都理解为正常流程之外的一种特例情况的处理；多次if-return，提前结束一些逻辑分支，可以提高代码思维的清晰性</li>
<li>requests的一些说明：1.get()发送get请求；2.返回结果r.status_code 获取返回状态吗；3.r.json()将返回结果序列化成json;4.r.text 将返回结果不做处理直接返回</li>
</ul>
<p><strong>从API获取数据</strong><br>将具体调用HTTP请求，获取结果的业务代码封装到YuShuBook中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">class YuShuBook:</span><br><span class="line"></span><br><span class="line">    search_by_isbn_url = &quot;http://t.yushu.im/v2/book/search/isbn/&#123;&#125;&quot;</span><br><span class="line"></span><br><span class="line">    search_by_key_url = &quot;http://t.yushu.im/v2/book/search?q=&#123;&#125;&amp;count=&#123;&#125;&amp;start=&#123;&#125;&quot;</span><br><span class="line"></span><br><span class="line">    @classmethod</span><br><span class="line">    def search_by_isbn(cls, isbn):</span><br><span class="line">        url = cls.search_by_isbn_url.format(isbn)</span><br><span class="line">        return HTTP.get(url)</span><br><span class="line"></span><br><span class="line">    @classmethod</span><br><span class="line">    def search_by_key(cls, q, count=15, start=0):</span><br><span class="line">        url = cls.search_by_key_url.format(q, count, start)</span><br><span class="line">        return HTTP.get(url)</span><br></pre></td></tr></table></figure></p>
<p>使用json.dumps 序列表返回结果，在视图函数中进行返回，并声明状态码和返回类型(一个元组)<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@app.route(&quot;/book/search/&lt;q&gt;/&lt;page&gt;&quot;)</span><br><span class="line">def search(q, page):</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    搜索书籍路由</span><br><span class="line">    :param q: 关键字 OR isbn</span><br><span class="line">    :param page: 页码</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    isbn_or_key = is_isbn_or_key(q)</span><br><span class="line">    if isbn_or_key == &apos;isbn&apos;:</span><br><span class="line">        result = YuShuBook.search_by_isbn(q)</span><br><span class="line">    else:</span><br><span class="line">        result = YuShuBook.search_by_key(q)</span><br></pre></td></tr></table></figure></p>
<pre><code>return json.dumps(result), 200, {&apos;content-type&apos;: &apos;application/json&apos;}
</code></pre><p>可以使用flask提供的jsonify替换的json.dumps和元组</p>
<pre><code>return jsonify(result)
</code></pre><h2 id="2-6-将视图函数拆分到单独的模块中"><a href="#2-6-将视图函数拆分到单独的模块中" class="headerlink" title="2.6 将视图函数拆分到单独的模块中"></a>2.6 将视图函数拆分到单独的模块中</h2><h3 id="1-将试图函数都放在一个文件中有哪些不足："><a href="#1-将试图函数都放在一个文件中有哪些不足：" class="headerlink" title="1.将试图函数都放在一个文件中有哪些不足："></a>1.将试图函数都放在一个文件中有哪些不足：</h3><p>1.代码太长，不利于维护<br>2.从业务模型抽象的角度，不应该把他们都放在一个文件中。关于书籍相关的API就应该放在书籍模型的视图函数文件中，跟用户相关的API就应该放在用户模型相关的文件中<br>3.入口文件的意义比较独特，会启动web服务器以及做很多初始化的操作，就算要放在一个文件也不应该业务的操作放在入口文件中来</p>
<h3 id="2-尝试拆分模块"><a href="#2-尝试拆分模块" class="headerlink" title="2.尝试拆分模块"></a>2.尝试拆分模块</h3><p>思路，将试图函数抽离到单独的包中，然后在新的试图文件中引入flask.py来导入app核心对象。为了新的试图文件中的路由可以成功注册，再在flask.py中引入刚刚抽离出的试图模块</p>
<p>修改后的fisher.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">from flask import Flask</span><br><span class="line"></span><br><span class="line"># 为了可以注册book.py中的路由</span><br><span class="line">from app.web import book</span><br><span class="line"></span><br><span class="line">app = Flask(__name__)</span><br><span class="line"></span><br><span class="line">app.config.from_object(&quot;config&quot;)</span><br><span class="line"></span><br><span class="line">if __name__ == &quot;__main__&quot;:</span><br><span class="line">app.run(host=app.config[&quot;HOST&quot;], debug=app.config[&quot;DEBUG&quot;], port=app.config[&quot;PORT&quot;])</span><br></pre></td></tr></table></figure>
<p>新增的book.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">from flask import jsonify</span><br><span class="line"></span><br><span class="line">from helper import is_isbn_or_key</span><br><span class="line">from yushu_book import YuShuBook</span><br><span class="line"></span><br><span class="line"># 为了让book.py模块可以使用app对象</span><br><span class="line">from fisher import app</span><br><span class="line"></span><br><span class="line">__author__ = &quot;gaowenfeng&quot;</span><br><span class="line"></span><br><span class="line">@app.route(&quot;/book/search/&lt;q&gt;/&lt;page&gt;&quot;)</span><br><span class="line">def search(q, page):</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">搜索书籍路由</span><br><span class="line">:param q: 关键字 OR isbn</span><br><span class="line">:param page: 页码</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">isbn_or_key = is_isbn_or_key(q)</span><br><span class="line">if isbn_or_key == &apos;isbn&apos;:</span><br><span class="line">result = YuShuBook.search_by_isbn(q)</span><br><span class="line">else:</span><br><span class="line">result = YuShuBook.search_by_key(q)</span><br><span class="line"></span><br><span class="line">return jsonify(result)</span><br></pre></td></tr></table></figure>
<p>但是这样做并不是正确的做法，结果表明，这样修改以后，访问search api会404</p>
<p>为了知道为什么这样做不行，我们需要先刨铣一下Flask路由机制的原理</p>
<h3 id="3-Flask路由机制"><a href="#3-Flask路由机制" class="headerlink" title="3.Flask路由机制"></a>3.Flask路由机制</h3><p>flask的基本思想是内部会维护一个字典。每一个url都会对应一个视图函数，但是不仅仅是这样。每一个url还会对应一个endpoint端点。用于反向构建URL（后面会讲解)</p>
<p>flask的路由注册<code>app_url_rule(url=,view_func=,endpoint=)</code>会接受三个参数，前两个我们都知道了，第三个就是上面说的endpoint。他的默认值是view_func的名称。当然，<code>app.route(&#39;url&#39;,endpoint=)</code>也可以传入</p>
<p>flask route的部分源码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"># 注册路由的装饰器</span><br><span class="line">def route(self, rule, **options):</span><br><span class="line">def decorator(f):</span><br><span class="line">endpoint = options.pop(&apos;endpoint&apos;, None)</span><br><span class="line"># 装饰器内部也是调用了add_url_rule</span><br><span class="line">self.add_url_rule(rule, endpoint, f, **options)</span><br><span class="line">return f</span><br><span class="line">return decorator</span><br><span class="line"># 注册路由</span><br><span class="line">@setupmethod</span><br><span class="line">def add_url_rule(self, rule, endpoint=None, view_func=None,</span><br><span class="line">provide_automatic_options=None, **options):</span><br><span class="line"></span><br><span class="line"># 如果endpoint传入的None，则使用视图函数名作为endpoint</span><br><span class="line">if endpoint is None:</span><br><span class="line">endpoint = _endpoint_from_view_func(view_func)</span><br><span class="line">options[&apos;endpoint&apos;] = endpoint</span><br><span class="line">methods = options.pop(&apos;methods&apos;, None)</span><br><span class="line"></span><br><span class="line"># 默认的method是GET请求</span><br><span class="line">if methods is None:</span><br><span class="line">methods = getattr(view_func, &apos;methods&apos;, None) or (&apos;GET&apos;,)</span><br><span class="line">if isinstance(methods, string_types):</span><br><span class="line">raise TypeError(&apos;Allowed methods have to be iterables of strings, &apos;</span><br><span class="line">&apos;for example: @app.route(..., methods=[&quot;POST&quot;])&apos;)</span><br><span class="line">methods = set(item.upper() for item in methods)</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line">...</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">rule = self.url_rule_class(rule, methods=methods, **options)</span><br><span class="line">rule.provide_automatic_options = provide_automatic_options</span><br><span class="line"></span><br><span class="line"># 将url-&gt;endpoint 的规则维护到url_map</span><br><span class="line">self.url_map.add(rule)</span><br><span class="line">if view_func is not None:</span><br><span class="line">old_func = self.view_functions.get(endpoint)</span><br><span class="line">if old_func is not None and old_func != view_func:</span><br><span class="line">raise AssertionError(&apos;View function mapping is overwriting an &apos;</span><br><span class="line">&apos;existing endpoint function: %s&apos; % endpoint)</span><br><span class="line"># 记录endpoint 所指向的view_func</span><br><span class="line">self.view_functions[endpoint] = view_func</span><br></pre></td></tr></table></figure>
<p>通过端点调试可以发现，Flask内部由url_map 维护一个url-&gt;endpoint 的指向。由view_functions 记录 endpoint所指向视图函数的函数，这样请求进入到Flask内部，才能通过Url找到对应的视图函数</p>
<h3 id="4-循环引入流程分析"><a href="#4-循环引入流程分析" class="headerlink" title="4. 循环引入流程分析"></a>4. 循环引入流程分析</h3><p>从上面的断点调试中发现，我们的url_maph和view_functions中都已经维护了相关的信息。但是为什么还是会出现404的情况，这是因为fisher.py和book.py出现了循环引入的情况。</p>
<p>下面看下fisher.py和book.py的具体流程图</p>
<p>回答流程图中的两个问题：<br>问题1：因为都是由fisher引入book，一个模块只会引入另一个模块一次。所以只执行了一次book<br>问题2：由于一次是主流程执行fisher文件；一次是由book模块导入 fisher。</p>
<h3 id="5-找不到视图函数的最终解释和证明"><a href="#5-找不到视图函数的最终解释和证明" class="headerlink" title="5.找不到视图函数的最终解释和证明"></a>5.找不到视图函数的最终解释和证明</h3><h5 id="整个流程中，出现了两次核心app对象的初始化，注册路由是在蓝色流程中初始化的app注册的。但是启动服务是红色流程中的app启动的"><a href="#整个流程中，出现了两次核心app对象的初始化，注册路由是在蓝色流程中初始化的app注册的。但是启动服务是红色流程中的app启动的" class="headerlink" title="整个流程中，出现了两次核心app对象的初始化，注册路由是在蓝色流程中初始化的app注册的。但是启动服务是红色流程中的app启动的"></a>整个流程中，出现了两次核心app对象的初始化，注册路由是在蓝色流程中初始化的app注册的。但是启动服务是红色流程中的app启动的</h5><h5 id="book中注册路由所使用的app对象，是他自己所导入fisher模块的app对象（蓝色流程中），而不是红色主流程中所实例化的app对象"><a href="#book中注册路由所使用的app对象，是他自己所导入fisher模块的app对象（蓝色流程中），而不是红色主流程中所实例化的app对象" class="headerlink" title="book中注册路由所使用的app对象，是他自己所导入fisher模块的app对象（蓝色流程中），而不是红色主流程中所实例化的app对象"></a>book中注册路由所使用的app对象，是他自己所导入fisher模块的app对象（蓝色流程中），而不是红色主流程中所实例化的app对象</h5><p>下面来加入一些日志出数验证我们的结论。我们在app实例化，启动，注册路由是哪个地方加入日志信息，来观察一下</p>
<p>book.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">print(&quot;id为&quot;+str(id(app))+&quot;的app注册路由&quot;)</span><br><span class="line"></span><br><span class="line">@app.route(&quot;/book/search/&lt;q&gt;/&lt;page&gt;&quot;)</span><br><span class="line">def search(q, page):</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">搜索书籍路由</span><br><span class="line">:param q: 关键字 OR isbn</span><br><span class="line">:param page: 页码</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">isbn_or_key = is_isbn_or_key(q)</span><br><span class="line">if isbn_or_key == &apos;isbn&apos;:</span><br><span class="line">result = YuShuBook.search_by_isbn(q)</span><br><span class="line">else:</span><br><span class="line">result = YuShuBook.search_by_key(q)</span><br><span class="line"></span><br><span class="line">return jsonify(result)</span><br></pre></td></tr></table></figure>
<p>fisher.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">app = Flask(__name__)</span><br><span class="line">print(&quot;id为&quot;+str(id(app))+&quot;的app实例化&quot;)</span><br><span class="line"></span><br><span class="line">app.config.from_object(&quot;config&quot;)</span><br><span class="line"></span><br><span class="line"># 为了可以注册book.py中的路由</span><br><span class="line">from app.web import book</span><br><span class="line"></span><br><span class="line">if __name__ == &quot;__main__&quot;:</span><br><span class="line">print(&quot;id为&quot; + str(id(app)) + &quot;的app启动&quot;)</span><br><span class="line">app.run(host=app.config[&quot;HOST&quot;], debug=app.config[&quot;DEBUG&quot;], port=app.config[&quot;PORT&quot;])</span><br></pre></td></tr></table></figure>
<p>执行结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">pydev debugger: process 63816 is connecting</span><br><span class="line"></span><br><span class="line">id为4350444824的app实例化</span><br><span class="line">id为4355159656的app实例化</span><br><span class="line">id为4355159656的app注册路由</span><br><span class="line">id为4350444824的app启动</span><br><span class="line">* Debugger is active!</span><br><span class="line">* Debugger PIN: 176-669-651</span><br></pre></td></tr></table></figure>
<p>可以看到注册路由的app，和启动服务的app不是同一个app。并且最后启动的app是最先实例化的app，而注册路由的app是后实例化的app，.</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/flask框架学习/windows下mysql的安装/" rel="next" title="windows下mysql的安装">
                <i class="fa fa-chevron-left"></i> windows下mysql的安装
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/flask框架学习/flask高级编程_鱼书项目_填坑记/" rel="prev" title="flask高级编程_鱼书项目_填坑记">
                flask高级编程_鱼书项目_填坑记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="WeiLai">
            
              <p class="site-author-name" itemprop="name">WeiLai</p>
              <p class="site-description motion-element" itemprop="description">好学近乎知，力行近乎仁，知耻近乎勇</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">132</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/itswl" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:imwl@live.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/6aa4c1b2a4a4" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-book"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.facebook.com/profile.php?id=100021764796181" target="_blank" title="Facebook">
                      
                        <i class="fa fa-fw fa-facebook"></i>Facebook</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-6-将视图函数拆分到单独的模块中"><span class="nav-number">1.</span> <span class="nav-text">2.6 将视图函数拆分到单独的模块中</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-将试图函数都放在一个文件中有哪些不足："><span class="nav-number">1.1.</span> <span class="nav-text">1.将试图函数都放在一个文件中有哪些不足：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-尝试拆分模块"><span class="nav-number">1.2.</span> <span class="nav-text">2.尝试拆分模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-Flask路由机制"><span class="nav-number">1.3.</span> <span class="nav-text">3.Flask路由机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-循环引入流程分析"><span class="nav-number">1.4.</span> <span class="nav-text">4. 循环引入流程分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-找不到视图函数的最终解释和证明"><span class="nav-number">1.5.</span> <span class="nav-text">5.找不到视图函数的最终解释和证明</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#整个流程中，出现了两次核心app对象的初始化，注册路由是在蓝色流程中初始化的app注册的。但是启动服务是红色流程中的app启动的"><span class="nav-number">1.5.0.1.</span> <span class="nav-text">整个流程中，出现了两次核心app对象的初始化，注册路由是在蓝色流程中初始化的app注册的。但是启动服务是红色流程中的app启动的</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#book中注册路由所使用的app对象，是他自己所导入fisher模块的app对象（蓝色流程中），而不是红色主流程中所实例化的app对象"><span class="nav-number">1.5.0.2.</span> <span class="nav-text">book中注册路由所使用的app对象，是他自己所导入fisher模块的app对象（蓝色流程中），而不是红色主流程中所实例化的app对象</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">WeiLai</span>

  
</div>


  <!--<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>

-->



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

  
</body>
</html>
